﻿using CommunityToolkit.Mvvm.Input;
using CSharpDevTools.Core;
using HandyControl.Controls;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace CSharpDevTools.ViewModels
{
    internal class ImageBase64ControlViewModel : EncodeBaseViewModel
    {
        private BitmapImage imageSource;

        public BitmapImage ImageSource
        {
            get =>this.imageSource;
            set => this.SetProperty(ref this.imageSource, value);
        }

        public RelayCommand OpenImageCmd => new RelayCommand(OpenImage);

        private void OpenImage()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片(*.jpg;*.png)| *.jpg;*.png";
            openFileDialog.Multiselect = false;
            if (openFileDialog.ShowDialog().Value)
            {
                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = File.OpenRead(openFileDialog.FileName);
                bmp.EndInit();
                this.ImageSource = bmp;
            }
        }

        protected override void Encode()
        {
            if (this.ImageSource == null)
            {
                MessageBox.Error("图片不能为空！", "错误");
                return;
            }

            this.EncodedData = Base64Helper.ToBase64(this.ImageSource);
        }

        protected override void Decode()
        {
            if (string.IsNullOrEmpty(this.EncodedData))
            {
                MessageBox.Error("编码后数据不能为空！", "错误");
                return;
            }

            this.ImageSource = Base64Helper.FromBase64(this.EncodedData);
        }
    }
}
